<?php

declare(strict_types=1);

namespace App\Job;
use App\Model\Applet;
use App\Model\DataPaymentCheckLog;
use App\Model\DataPaymentRefund;
use App\Model\DataPaymentRefundLog;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Psr\Log\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
class DyRefundOrderJob extends Job
{

    const refundReason =[
        0 =>'暂无描述',
        1 =>'产品问题，影响使用或效果不佳',
        2 =>'售后问题，无法满足需求',
        3 =>'意愿问题，用户主动退款',
        4 =>'价格问题',
        5 =>'其他原因',
    ];

    public $ids;

    public $redis;
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $getOrderUrl = "https://open.douyin.com/api/trade_basic/v1/developer/order_query";

    public static $refundUrl = "https://open.douyin.com/api/trade_basic/v1/developer/refund_create/";

    public function __construct($refund_id,$paymentInfo,$handle_User_id,$refund_reason)
    {
        $container = ApplicationContext::getContainer();
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'dyRefundOrder');
        $this->refund_id = $refund_id;
        $this->paymentInfo = $paymentInfo;
        $this->handle_user_id = $handle_User_id;
        $this->refund_reason = $refund_reason;
    }

    public function handle()
    {
        $refund_id = $this->refund_id;
        $paymentInfo = $this->paymentInfo;
        $handle_User_id = $this->handle_user_id;
        try {
            $this->logger->info('开始提交订单退款逻辑');
            //查询小程序的key
            $appletInfo = Applet::query()->where('id',$paymentInfo->applet_id)->select(['id','AppKey','app_id','app_secret'])->first();
//            $accessToken = env('DY_TEST_TOKEN');
            $accessToken = $this->getDyAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
            if(!empty($accessToken)){
                $orderResult = $this->checkDyOrder($handle_User_id, $paymentInfo->id,$paymentInfo->order_id,$accessToken);
                if($orderResult['err_no'] == 0){
                    $orderInfo = $orderResult['data'];
//
                    $refund_order_id = $this->getReturnOrderId($paymentInfo->applet_id,$paymentInfo->user_id,$paymentInfo->goods_id);
//
                    $returnOrderResult = $this->refundDyOrder($handle_User_id,$paymentInfo->id,$orderInfo['order_id'],
                        $refund_order_id,$accessToken,$paymentInfo->amount,$orderInfo['item_order_list'],$this->refund_reason);
//
                    var_dump($orderInfo);
                    if($returnOrderResult['err_no'] == 0){

                        $returnOrderInfo = $returnOrderResult['data'];
                        $returnOrderInfo['refund_order_id'] = $refund_order_id;
                        $this->UpdateRefundData($handle_User_id,$refund_id,$returnOrderInfo,2);
                    }else{
                        $this->UpdateRefundData($handle_User_id,$refund_id,$returnOrderResult,4,$returnOrderResult['err_msg']);
                    }
                }else{
                    $this->logger->error('查询线抖音信订单错误',[]);
                    $this->UpdateRefundData($handle_User_id,$refund_id,array(),4,'查询线上抖音订单错误');
                }
            }else{
                $this->logger->error('抖音token问题',[$accessToken]);
                $this->UpdateRefundData($handle_User_id,$refund_id,array(),4,'抖音token问题');
            }
        }catch (\Exception $e){
            $this->logger->error('请求抖音退款订单|错误：' . $e->getLine() . '|' . $e->getMessage());
            $this->UpdateRefundData($handle_User_id,$refund_id,array(),4,'请求抖音退款订单|错误'.$e->getMessage());
        }
    }

    public function UpdateRefundData($handle_User_id,$refund_id,$orderInfo,$status=1,$refund_order_msg = ''){


        $refund_order_id = $orderInfo['refund_order_id'] ?? 0;
        $refund_dy_order_id = $orderInfo['refund_id'] ?? 0;

        DataPaymentRefund::query()->where(['id' => $refund_id])->update([
            'handle_User_id' => $handle_User_id,
            'refund_order_id' => $refund_order_id,
            'status' => $status,
            'refund_dy_order_id' => $refund_dy_order_id,
            'refund_order_msg' => $refund_order_msg
        ]);
    }

    /**
     * 检查抖音订单
     */
    public function checkDyOrder($click_user_id,$payment_id,$order_id,$accessToken){

        $params = [
            'out_order_no'=>$order_id,
        ];
        $url = self::$getOrderUrl;
        $orderResult  = $this->request($params,$url, 'POST',$accessToken);
        if($orderResult['err_no'] == 0){
            $return_msg = '获取成功';
        }else{
            $return_msg = $orderResult['err_msg'];
        }
        //插入日志
        $this->installCreateLog($click_user_id,$payment_id,$return_msg,$orderResult,$url,$params,1);
        return $orderResult;

    }

    /**
     * 插入查看日志
     */
    public function installCreateLog($user_id,$payment_id,$return_msg,$reutrnData,$request_url,$request_params,$type){

        $return_text = json_encode($reutrnData);
        $request_params = json_encode($request_params);
        DataPaymentCheckLog::Create([
            'user_id' => $user_id,
            'payment_id' => $payment_id,
            'return_msg' => $return_msg,
            'return_text' => $return_text,
            'request_url' => $request_url,
            'request_params' => $request_params,
            'type' => $type,
        ]);
    }

    /**
     * 退款微信订单
     */
    public function refundDyOrder($click_user_id,$payment_id,$order_id,$refund_order_id,$accessToken,$amount,$item_order_list,$refund_reason){


        $params = [
            'cp_extra' => 'dy_refund_info',
            'order_entry_schema' => [
                'path' => 'pages/index/index'
            ],
            'order_id' => $order_id,
            'out_refund_no' => $refund_order_id,
            'item_order_detail' =>[[
                'item_order_id' => $item_order_list[0]['item_order_id'],
                'refund_amount' => $item_order_list[0]['item_order_amount'],
            ]],
            'refund_reason'   => [[
                'code' => 999,
                'text' => self::refundReason[$refund_reason]]
            ],
            'refund_total_amount' => $amount
        ];
        $refundUrl = self::$refundUrl;
        $this->logger->info('请求退款数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求退款Url：'.$refundUrl);
        $refundResult  = $this->request($params,$refundUrl, 'POST',$accessToken);
        if($refundResult['err_no'] == 0){
            $this->logger->info('调用退款接口成功 返回数据：'.PHP_EOL.var_export(['result' => $refundResult], true));
            $this->installRefundLog($click_user_id,$payment_id,'获取成功',$refundResult,$refundUrl,$params);
            return $refundResult;
        }else{
            $this->logger->error('调用退款接口失败 返回数据：'.PHP_EOL.var_export(['result' => $refundResult], true));
            return $refundResult;
        }
    }

    /**
     * 插入退款日志
     */
    public function installRefundLog($user_id,$payment_id,$return_msg,$reutrnData,$request_url,$request_params){

        $return_text = json_encode($reutrnData);
        $request_params = json_encode($request_params);
        DataPaymentRefundLog::Create([
            'user_id' => $user_id,
            'payment_id' => $payment_id,
            'return_msg' => $return_msg,
            'return_text' => $return_text,
            'request_url' => $request_url,
            'request_params' => $request_params,
        ]);
    }
    /**
     * 获取退款订单ID
     */
    public function getReturnOrderId($applet_id,$user_id,$goods_id){
        $order_id = 'R'.time().mt_rand(10000,99999).$applet_id.$user_id.$goods_id;
        return $order_id;
    }

    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
//        var_dump($redis->ttl($key));
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}